local S_Castself_Tooltip = AceLibrary("Gratuity-2.0")

function S_ToggleSelfCast()
	if (CS_SELF_ENABLED) then
		CS_SELF_ENABLED = false
		print("已关闭自动自我施法")
	else
		CS_SELF_ENABLED = true
		SetCVar("autoSelfCast", 0)	-- 关闭系统默认自动自我施法
		print("已开启自动自我施法，使用ALT强行对自己施法")
	end
end

SLASH_SCS1 = "/scastself"
SlashCmdList["SCS"] = S_ToggleSelfCast

local function SelfCast()
	if (CS_SELF_ENABLED) then
		return IsAltKeyDown()
	else
		return 0
	end
end

local function GetActionItemInfo(slot)
	S_Castself_Tooltip:SetAction(slot)
	local line1 = S_Castself_Tooltip:GetLine(1)
	local bags, slots = FindItemInfo(line1)
	return line1, bags, slots
end

--hook UseAction函数
local S_UseAction = UseAction
function S_CastSelf_UseAction(slot, type, onSelf)
	local isSelfCast = onSelf or SelfCast()

	if not UnitIsFriend("player", "target") then  --如果目标友善
		if isSelfCast and SpellCanTargetUnit("player") then
			local line1, bags, slots = GetActionItemInfo(slot)
			if (line1 and bags and slots) then
				UseContainerItem(bags, slots)
				return
			end
			S_UseAction(slot, type, isSelfCast)
		else
			S_UseAction(slot, type, isSelfCast)
			if CS_SELF_ENABLED then
				SpellTargetUnit("player")
			end
		end
	else
		if isSelfCast and (not CursorHasItem()) and (not CursorHasSpell()) then
			local _, bags, slots = GetActionItemInfo(slot)
			if (bags and slots) then
				UseContainerItem(bags, slots)
				return
			end
			S_UseAction(slot, type, isSelfCast)
		else
			S_UseAction(slot, type, isSelfCast)
			if CS_SELF_ENABLED then
				SpellTargetUnit("player")
			end
		end
	end
end
UseAction = S_CastSelf_UseAction

--hook UseContainerItem函数
local S_UseContainerItem = UseContainerItem
function S_CastSelf_UseContainerItem(bagId, slot, onSelf)
	local isSelfCast = onSelf or SelfCast()

	if not UnitIsFriend("player", "target") then  --如果目标友善
		if isSelfCast and SpellCanTargetUnit("player") then
			S_UseContainerItem(bagId, slot, isSelfCast)
		else
			S_UseContainerItem(bagId, slot, isSelfCast)
			if CS_SELF_ENABLED then
				SpellTargetUnit("player")
			end
		end
	else
		if isSelfCast and (not CursorHasItem()) and (not CursorHasSpell()) then
			S_UseContainerItem(bagId, slot, isSelfCast)
		else
			S_UseContainerItem(bagId, slot, isSelfCast)
			if CS_SELF_ENABLED then
				SpellTargetUnit("player")
			end
		end
	end
end
UseContainerItem = S_CastSelf_UseContainerItem
